package com.shizhanzhe.zxbapp.home;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.dpuntu.downloader.DownloadManager;
import com.dpuntu.downloader.Downloader;
import com.dpuntu.downloader.Observer;
import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.shizhanzhe.zxbapp.R;
import com.shizhanzhe.zxbapp.base.BaseApplication;
import com.shizhanzhe.zxbapp.bean.AppDetail;
import com.shizhanzhe.zxbapp.bean.UserBean;
import com.shizhanzhe.zxbapp.customtask.PictureUploadDetailsActivity;
import com.shizhanzhe.zxbapp.ui.LoginActivity;
import com.shizhanzhe.zxbapp.url.Path;
import com.shizhanzhe.zxbapp.utils.DownUtil;
import com.shizhanzhe.zxbapp.utils.OkHttpDownloadJsonUtil;
import com.shizhanzhe.zxbapp.utils.SharedPreferencesUtils;
import com.shizhanzhe.zxbapp.utils.Util;
import com.shizhanzhe.zxbapp.widget.MyListView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.OkHttpClient;

/**
 * Created by zz9527 on 2018/11/14.
 */
public class AppDetailActivity extends Activity implements View.OnClickListener {
    private ImageView appIcon;

    private TextView rewardCount;

    private TextView appName;

    private TextView appVersion;

    private TextView appSize;
    private TextView total;
    private TextView vipdivide;
    private Button openOrDownloadBtn;

    private ProgressBar downlaodProgressBar;

    private SmartRefreshLayout refresh; // 下拉刷新组件

    private MyListView listView;
    private Handler mHandler = new Handler(Looper.getMainLooper());
    private String packageName = "";
    private String baoming = "";
    private String proid;
    private String taskId = "";
    private int type = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.acticity_taskdetail);
        ImmersionBar.with(this).statusBarColor(R.color.them)
                .init();
        File appDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/ZXBFile");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String[] app = getIntent().getStringExtra("app").split("#");
        proid = app[1];
        baoming = app[2];
        packageName = (String) SharedPreferencesUtils.getParam(getApplicationContext(), "packName", "");
        taskId = (String) SharedPreferencesUtils.getParam(this, "taskId", "");
        // 初始化View
//        initView(proid);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ImmersionBar.with(this).destroy(); //必须调用该方法，防止内存泄漏
    }

    private void initView(final String proid) {
        refresh = findViewById(R.id.refresh);
        refresh.setRefreshHeader(new MaterialHeader(this));
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
                requestDetailData(proid);
            }
        });
        findViewById(R.id.backarea).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        listView = findViewById(R.id.detailpage_listview);
        total = findViewById(R.id.tv_detailpage_total);
        vipdivide = findViewById(R.id.tv_detailpage_vip);
        appIcon = (ImageView) findViewById(R.id.iv_detailpage_appicon);
        appName = (TextView) findViewById(R.id.tv_detailpage_appname);
        appVersion = (TextView) findViewById(R.id.tv_detailpage_apppvn);
        appSize = (TextView) findViewById(R.id.tv_detailpage_appsize);

        rewardCount = (TextView) findViewById(R.id.tv_detailpage_rewards_count);
        findViewById(R.id.backarea).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        downlaodProgressBar = (ProgressBar) findViewById(R.id.pb_download);
        downlaodProgressBar.setVisibility(View.GONE);
        openOrDownloadBtn = (Button) findViewById(R.id.btn_detailpage_open_or_install);
        openOrDownloadBtn.setVisibility(View.INVISIBLE);
        openOrDownloadBtn.setOnClickListener(this);

        if (Util.isPackageExist(this, baoming)) {
            //已安装
            openOrDownloadBtn.setText("打开");
        } else if (packageName.contains("andriod" + proid + ".apk")) {
            //已下载，未安装
            openOrDownloadBtn.setText("安装");
        } else if (taskId.contains(proid)) {
            //继续下载
            openOrDownloadBtn.setText("继续");
        } else {
            //下载
            openOrDownloadBtn.setText("下载");
        }
        DownloadManager.subjectTask(proid, new DownloadObserver(downlaodProgressBar, openOrDownloadBtn));
        requestDetailData(proid);
    }
    AppDetail appDetail;
    private void requestDetailData(String proid) {
        OkHttpDownloadJsonUtil.downloadJson(this, Path.APPDETAIL(proid, UserBean.uid), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
            @Override
            public void onsendJson(String json) {
                if (!"1".equals(json) && !"2".equals(json)) {
                    Gson gson = new Gson();
                    appDetail = gson.fromJson(json, AppDetail.class);
                    openOrDownloadBtn.setVisibility(View.VISIBLE);
                    appName.setText(appDetail.getData().getProname());
                    appVersion.setText("版本号：" + appDetail.getData().getBaonumber());
                    appSize.setText("大小：" + appDetail.getData().getBaosize());
                    List<AppDetail.DetailBean> list=new ArrayList<>();
                    if (appDetail.getData().getProtasktype()==0) {
                        total.setText("+" + appDetail.getData().getDaninstall() + "元");
                        list.add(new AppDetail.DetailBean("下载安装APP",appDetail.getData().getDaninstall(),0)) ;
                    }else {
                        list.addAll(appDetail.getDetail());
                        total.setText("+" + appDetail.getTotalamount() + "元");
                    }
                    vipdivide.setVisibility(View.GONE);
                    listView.setAdapter(new AppDetailAdapter(AppDetailActivity.this, list, Double.parseDouble(appDetail.getData().getDaninstall())));
                    refresh.finishRefresh(false);
                    Glide.with(getApplicationContext()).load(Path.img(appDetail.getData().getAppicon())).apply(new RequestOptions().error(R.mipmap.logo)).into(appIcon);
                    rewardCount.setText("已有 " + appDetail.getData().getAppdown() + "个用户下载");
                    type = appDetail.getData().getProtasktype();
                } else {
                    Toast.makeText(AppDetailActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_detailpage_open_or_install:
                if (UserBean.uid == 0) {
                    startActivity(new Intent(AppDetailActivity.this, LoginActivity.class));
                } else {
                    switch (openOrDownloadBtn.getText().toString()) {
                        case "下载":
                            if (type == 0) {
                                down();
                            } else {
                                depth();
                            }
                            break;
                        case "安装":
                            File savedFile = new File(Environment.getExternalStorageDirectory().toString()
                                    + "/ZXBFile/andriod" + proid + ".apk");
                            if (savedFile.exists()) {
                                DownUtil.installAPK(this, savedFile);
                            } else {
                                down();
                            }
                            break;
                        case "打开":
                            DownUtil.openApp(this, baoming);
                            break;
                        case "继续":
                            DownloadManager.start(proid);
                            break;
                        default:
                            //下载中，暂停
                            DownloadManager.pause(proid);
                            break;
                    }
                    DownloadManager.subjectTask(proid, new DownloadObserver(downlaodProgressBar, openOrDownloadBtn));
                    break;
                }

                break;

            default:
                break;
        }
    }

    private void depth() {
        OkHttpDownloadJsonUtil.downloadJson(this, Path.DEPTH(proid, UserBean.uid, Util.androidId(this)), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
            @Override
            public void onsendJson(String json) {
                down();
            }
        });
    }

    //下载
    private void down() {
        Log.i("__________", Path.BASE_URL + appDetail.getData().getProapk());
        List<Downloader> downloaders = new ArrayList<Downloader>();
        OkHttpClient client = new OkHttpClient.Builder().build();
        Downloader downloader = new Downloader.Builder()
                .client(client)
                .fileName("andriod" + proid + ".apk")
                .filePath(Environment.getExternalStorageDirectory().getPath() + "/ZXBFile")
                .taskId(proid)
                .url(Path.BASE_URL + appDetail.getData().getProapk())
                .build();
        downloaders.add(downloader);
        DownloadManager.addDownloader(downloaders);
        DownloadManager.start(proid);
        if (null == taskId | !taskId.contains(proid)) {
            if (taskId.equals("")) {
                SharedPreferencesUtils.setParam(this, "taskId", proid);
            } else {
                SharedPreferencesUtils.setParam(this, "taskId", taskId + ";" + proid);
            }
        }
    }

    private class DownloadObserver implements Observer {
        private ProgressBar mTextView;
        private TextView textView;

        public DownloadObserver(ProgressBar textView, TextView textView1) {
            mTextView = textView;
            this.textView = textView1;
        }

        @Override
        public void onCreate(String s) {

        }

        @Override
        public void onReady(String s) {

        }

        @Override
        public void onLoading(String s, final String s1, final long l, final long l1) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    mTextView.setVisibility(View.VISIBLE);
                    mTextView.setProgress((int) (((double) l1 / (double) l) * 100));
                    textView.setText((String.format("正在下载,已完成%d%% ,下载速度: %s", (int) (((double) l1 / (double) l) * 100), s1)));
                }
            });
        }

        @Override
        public void onPause(String s, final long l, final long l1) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    mTextView.setProgress((int) (((double) l1 / (double) l) * 100));
                    textView.setText("继续");
                }
            });
        }

        @Override
        public void onFinish(String s) {
            DownloadManager.removeTaskObserver(s, this);
            // 最好不要在这里做这一步操作，因为你可能绑定了其他监听者，有一处移除，其他的均无法监听甚至出现异常
            //  DownloadManager.remove(taskId);
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    mTextView.setProgress(100);
                    mTextView.setVisibility(View.GONE);
                    textView.setText("安装");
                    File file = new File(Environment.getExternalStorageDirectory().toString()
                            + "/ZXBFile/andriod" + proid + ".apk");
                    SharedPreferencesUtils.setParam(getApplicationContext(), "packName", packageName + "andriod" + proid + ".apk");
                    DownUtil.installAPK(getApplicationContext(), file);
                }
            });
        }

        @Override
        public void onError(String s, String s1, long l, long l1) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(), "下载异常", Toast.LENGTH_SHORT).show();
                    textView.setText("下载");
                }
            });
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        initView(proid);
    }
}
